<template>
	<div>
		<!-- 退款申请弹窗dialogApply -->
		
			<div>
				<div>
					<el-form class="pt20 plr20" style="padding-bottom: 0;" :rules="rules" :model="form" ref="refForm"
						:inline="true">
						<el-form-item label="关联客户" prop="customerName" style="margin-right: 18px;">
							<el-input @focus="chooseCustomer" v-model="form.customerName" placeholder="请选择" clearable
								class="resetInput" style="width: 200px" />
						</el-form-item>
						<el-form-item label="是否退货" prop="refundType" style="margin-right: 0;">
							<el-radio-group v-model="form.refundType">
								<el-radio v-for="dict in returnType" :key="dict.value" :label="dict.value"
									:value="dict.value" size="large" style="margin-right: 15px;">
									{{dict.label}}
								</el-radio>
							</el-radio-group>
						</el-form-item>
						<div v-if="form.refundType != 2">
							<div class="flex col-center row-between">
								<div class="fs16 color333">
									<span class="color-red">*</span>
									<span class="fb mr20">退货商品</span>
								</div>
								<el-button class="mt5" type="defaultBtn" @click="handleGoods()">添加商品</el-button>
							</div>
							<div class="mt10 mb20" >
								<el-table :data="form.commondityList" style="width: 100%;text-align: center;"
									:cell-style="{ textAlign: 'center','line-height':'54px'}"
									:header-cell-style="{ 'text-align': 'center','line-height':'54px','height':'54px!important'  }">
									<el-table-column prop="commondityName" label="商品名称" />
									<el-table-column prop="commondityUnit" label="商品单位">
										<template v-slot="scope">
											{{scope.row.commondityUnit}}
										</template>
									</el-table-column>
									<el-table-column label="商品价格" width="200px">
										<template #default="scope">
											<el-form-item prop="commondityPrice" style="margin-right: 0;margin-top: 18px;">
												<el-input type="number" v-model="scope.row.commondityPrice"
													style="width: 120px" size="large" placeholder="请输入" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column label="退货数量" width="200px">
										<template #default="scope">
											<el-form-item prop="commondityCount" style="margin-right: 0;margin-top: 18px;">
												<el-input type="number" v-model="scope.row.commondityCount"
													style="width: 120px" size="large" placeholder="请输入" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column fixed="right" label="操作" align="center"
										class-name="small-padding fixed-width">
										<template #default="scope">
											<el-button link style="color: red!important;" type="primary"
												@click="delGoods(scope.$index)">删除</el-button>
										</template>
									</el-table-column>
								</el-table>
							</div>
						</div>
						<el-form-item label="退款金额" prop="refundAmount" style="margin-right: 22px;">
							<el-input v-model="form.refundAmount" placeholder="请输入" clearable class="resetInput"
								style="width: 228px" />
						</el-form-item>
						<el-form-item label="物流单号" label-width="100px" prop="logisticsTrackingNumber"
							style="margin-right: 0;">
							<el-input v-model="form.logisticsTrackingNumber" placeholder="请输入" clearable
								class="resetInput" style="width: 228px" />
						</el-form-item>
						<el-form-item label="业务经理" prop="businessManager">
							<el-select v-model="form.businessManager" placeholder="请选择" size="large"
								style="width:228px">
								<el-option v-for="dict in teamOptions" :key="dict.userId" :label="dict.userName"
									:value="dict.userId" />
							</el-select>
							<!-- <el-input v-model="form.businessManager" placeholder="请输入" clearable class="resetInput"
							style="width: 630px;" /> -->
						</el-form-item>
						<el-form-item label="用友退款单号" label-width="100px" prop="returnGoodsOrderNumber"
							style="margin-right: 0;">
							<el-input v-model="form.returnGoodsOrderNumber" placeholder="请输入" clearable
								class="resetInput" style="width: 228px" />
						</el-form-item>
						<el-form-item label="退款描述" prop="supervisorApprovalRemark">
							<el-input size="large" type="textarea" resize="none" class="textReset" style="width: 630px;"
								:rows="5" v-model="form.supervisorApprovalRemark" placeholder="请输入退款描述" />
						</el-form-item>
						<el-form-item label="上传附件" prop="uploadAttachment">
							<div>
								<el-upload name="file" :action="url" :headers="headers" :show-file-list="false"
								:limit='1'
								accept=".jpg,.rar,.zip,.doc,.docx,.pdf"
									:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
									:file-list="fileList" :before-remove="beforeRemove">
									<el-button class="cancelSubBtn">上传附件</el-button>
								</el-upload>
								<div class="flex col-center row-between" v-if="form.uploadAttachment">
									<div class="text-line-1 mr5" style="max-width: 500px;">
										<a class="main-color" :href="form.uploadAttachment"
											target="_blank">{{form.uploadAttachment}}</a>
									</div>
									<el-icon class="cursor color" @click="form.uploadAttachment = ''">
										<CircleClose />
									</el-icon>
								</div>
								<div>
									支持格式：.rar .zip .doc .docx .pdf .jpg等，单个文件不能超过20MB！
								</div>
							</div>
						</el-form-item>
					</el-form>
				</div>
				<div slot="footer" class="dialog-footer text-right mt30">
					<el-button class="cancelSubBtn" @click="close()">取 消</el-button>
					<el-button type="primary" @click="handleAddRefund('refForm')" class="mainSubBtn">确 定</el-button>
				</div>
			</div>
		
		<!-- 客户弹窗 -->
		<customerList ref="customerDialog" @customerFunc="customerFunc"></customerList>
		<!-- 商品弹窗 -->
		<goodsListPop ref="goodsDialog" :propIds="ids" @getGoodsList="getGoodsList"></goodsListPop>
	</div>
</template>

<script>
	import {
		getUserListData //查业务经理
	} from "@/api/business/teamOpportunity";
	import {
		refundAdd,// 新增退款申请
		refundEdit,//编辑提交
		refundDetail,//详情
		tNumberUpdate//更新用友单号
	} from "@/api/business/refund";
	import customerList from "@/components/customer/index.vue"//客户
	import goodsListPop from "@/components/goods/index.vue"//订单
	import {
		getToken
	} from "@/utils/auth";
	let url = import.meta.env.VITE_APP_BASE_API + "/common/upload"
	export default {
		components: {
			customerList,
			goodsListPop,
		},
		data() {
			return {
				headers: {
					Authorization: 'Bearer ' + getToken() // 这里的getToken方法需要你自己实现，用于获取你的Token
				},
				url: url,
				dialogVisible: false,
				teamOptions: [], //人员
				returnType: [{
						value: 0,
						label: '全部退货'
					},
					{
						value: 1,
						label: '部分退货'
					},
					{
						value: 2,
						label: '无需退货'
					}
				], //退款类型
				form: {
					id: '',
					customerId: '', //客户ID
					refundType: 0, //是否退货（0全部退或，1部分退款 2无需退回）
					logisticsTrackingNumber: '', //物流单号
					returnGoodsOrderNumber:'',//用友单号
					businessManager: '', //业务经理id
					refundDescription: '', //退款描述
					uploadAttachment: '', //上传附件
					submissionTime: '', //提交时间
					supervisorApprovalRemark: '', //业务退款描述
					refundAmount: '', //退款金额
					commondityList: [] // 商品列表
				},
				rules: {
					// businessManager: [{
					// 	required: true,
					// 	message: '请选择业务经理',
					// 	trigger: 'change'
					// }, ],
					refundAmount: [{
						required: true,
						message: '请输入退款金额',
						trigger: 'blur'
					}, ],
					customerName: [{
						required: true,
						message: '请选择关联客户',
						trigger: 'blur'
					}, ]
				},	
				ids:[]
			}
		},
		created() {
			this.getUserList()
		},
		methods: {
			handleAvatarSuccess(e) {
				this.form.uploadAttachment = e.url
			},
			beforeAvatarUpload(e) {
				console.log(e, 'e2')
				let size = e.size / 1024 / 1024 
				if(size > 20){
					this.form.uploadAttachment = ''
					this.$modal.msgError('文件不能超过20MB！')
					return false;
				}
			},
			// 获取业务经理
			getUserList() {
				//获取自己和同部门的用户信息
				getUserListData().then(response => {
					this.teamOptions = response.data;
				});
			},
			//添加商品
			handleGoods(){
				this.ids = []
				for(let key in this.form.commondityList){
					this.ids.push(this.form.commondityList[key].commondityId) 
				}
				console.log(this.ids,'ids====')
				this.$refs.goodsDialog.open()
			},
			
			//获取商品
			getGoodsList(goodsList){
				let arr = []
				for(let key in goodsList){
					let item = {
						commondityId: '', //商品id
						commondityCount: '', //商品数量
						commondityName: '', //商品名称
						commondityUnit: '', //商品单位
						commondityPrice: '', //商品价格
						remark: '', //备注
						refundNumber: '' //退款编码
					}
					item.commondityId = goodsList[key].id
					item.commondityName = goodsList[key].commodityName
					item.commondityUnit = goodsList[key].minUnit
					arr.push(item)
				}
				console.log(arr,'arr=======')
				for(let key in this.form.commondityList){
					for(let j in arr){
						if(arr[j].commondityId == this.form.commondityList[key].commondityId){
							arr.splice(j,1)
						}
					}
				}
				this.form.commondityList = this.form.commondityList.concat(arr)
			},
			
			//删除商品
			delGoods(index){
				this.form.commondityList.splice(index,1)
				this.$forceUpdate()
			},
			//新增退款申请
			handleAddRefund(formName){
				//需要退货校验
				if(this.form.refundType != 2){
					if(this.form.commondityList.length == 0){
						this.$modal.msgError('请选择商品')
						return false;
					}
					for(let key in this.form.commondityList){
						if(this.form.commondityList[key].commondityPrice == '' || this.form.commondityList[key].commondityPrice <= 0){
							this.$modal.msgError('请检查商品价格')
							return false;
						}else if(this.form.commondityList[key].commondityCount == '' || this.form.commondityList[key].commondityCount*1 <= 0){
							this.$modal.msgError('请检查退货数量')
							return false;
						}
					}
				}else{
					//无需退货
					this.form.commondityList = []
				}
				
				this.$refs[formName].validate((valid) => {
					if (valid) {
						if(this.form.id == ''){
							refundAdd(this.form).then(res=>{
								this.$modal.msgSuccess('添加成功')
								this.dialogVisible = false
								this.$emit('getList')
							})
						}else{
							refundEdit(this.form).then(res=>{
								this.$modal.msgSuccess('编辑成功')
								this.dialogVisible = false
								this.$emit('getList')
							})
						}
					}
				})	
			},
			// 关联客户
			chooseCustomer() {
				// this.checkDialog = false
				this.$refs.customerDialog.open()
			},
			//获取选中的客户信息
			customerFunc(e) {
				this.form.customerId = e.id
				this.form.customerName = e.name
			},
			handleClose() {
				this.dialogVisible = false
			},
			open(num) {
				this.form = {
					id: '',
					customerId: '', //客户ID
					refundType: 0, //是否退货（0全部退或，1部分退款 2无需退回）
					logisticsTrackingNumber: '', //物流单号
					returnGoodsOrderNumber:'',//用友单号
					businessManager: '', //业务经理id
					refundDescription: '', //退款描述
					uploadAttachment: '', //上传附件
					submissionTime: '', //提交时间
					supervisorApprovalRemark: '', //业务退款描述
					refundAmount: '', //退款金额
					commondityList: [
						// {
						// 	commondityId: '', //商品id
						// 	commondityCount: '', //商品编码
						// 	commondityName: '', //商品名称
						// 	commondityUnit: '', //商品单位
						// 	commondityPrice: '', //商品价格
						// 	commondityBatch: '', //商品批次
						// 	remark: '', //备注
						// 	refundNumber: '' //商品数量
						// },						
					] // 商品列表
				}
				this.dialogVisible = true
				if(num != ''){
					this.detail(num)
				}
			},
			close(){
				this.$emit('handleClose')
			},
			//详情
			detail(id){
				refundDetail(id).then(res=>{
					// this.dialogVisible = true
					this.form = res.data
					
				})
			}
		}
	}
</script>

<style>
</style>